from xml.dom.minidom import parse
import xml.dom.minidom
import gzip


class Node:
    def __init__(self, name, version):
        self.name = name
        self.ver = version
        self.req = []
        self.haschildren = False
        self.children = []
        self.level = -1

    def addReq(self, new):
        self.req.append(new)

    def __str__(self):
        return self.name


def find(N_List, n, v):
    for i in N_List:
        if n == i.name:
            if i.ver == 'no' and v != 'no':
                i.ver = v   # 考虑安全性, 更新其版本
            return i

    return None


def printTree(Head_List):
    tmpList = Head_List
    tmpList2 = []
    while len(tmpList) != 0:
        for i in tmpList:
            for j in i.req:
                tmpList2.append(j)
        print(len(tmpList))
        tmpList = tmpList2
        tmpList2 = []


file_name = "./UpData/523ec3918c22e506e8a58fd5e73c7206dc406820f6cd5276b9e622962a8b79f4-primary.xml.gz"
f_name = file_name.replace(".gz", "")
g_file = gzip.GzipFile(file_name)
open(f_name, "wb+").write(g_file.read())
g_file.close()


# 使用minidom解析器打开 XML 文档
DOMTree = xml.dom.minidom.parse(
    "./UpData/523ec3918c22e506e8a58fd5e73c7206dc406820f6cd5276b9e622962a8b79f4-primary.xml")

# DOMTree = xml.dom.minidom.parse("..\\dataCrawl\\523ec3918c22e506e8a58fd5e73c7206dc406820f6cd5276b9e622962a8b79f4-primary"
#                                 ".xml\\a.xml")

collection = DOMTree.documentElement

packages = collection.getElementsByTagName("package")

nodeList = []

for p in packages:
    # print("*****Package*****")
    name = p.getElementsByTagName('name')[0]
    name = name.childNodes[0].data
    ver = p.getElementsByTagName('version')[0]
    ver = ver.getAttribute('ver')
    if find(nodeList, name, ver) is not None:
        # print(name.childNodes[0].data)
        ne = find(nodeList, name, ver)
    else:
        ne = Node(name, ver)    # 不同的版本也会有不同的节点, 但是ver是’no‘时不区分版本号
        nodeList.append(ne)
    # print("name: %s-%s-%s" % (name.childNodes[0].data, ver.getAttribute('ver'), ver.getAttribute('rel')))

    rpm_list = p.getElementsByTagName('rpm:entry')
    for rpm in rpm_list:    # 包依赖中会出现奇怪的现象：例如包gdp的依赖中有一个也叫gdp，而且这个gdp没有版本信息。处理：跳过该依赖？
        # print("req -> %s" % rpm.getAttribute("name"))
        if rpm.getAttribute('name') == ne.name:
            continue
        if rpm.getAttribute('ver') != '':
            ver = rpm.getAttribute('ver')
        else:
            ver = 'no'
        nodeReq = find(nodeList, rpm.getAttribute('name'), ver)
        if nodeReq is not None:
            nodeReq.haschildren = True
            nodeReq.children.append(ne)
        else:
            nodeReq = Node(rpm.getAttribute('name'), ver)
            nodeReq.haschildren = True
            nodeReq.children.append(ne)
            nodeList.append(nodeReq)
        ne.addReq(nodeReq)

c = 0
h = []
for i, n in enumerate(nodeList):
    if n.haschildren is False:
        h.append(n)
        c = c + 1

# print(c)
print(len(nodeList))
# printTree(h)
for i in nodeList:
    print(i.name, end='')
    print(' -> in: ', end='')
    print(len(i.children), end='  ')
    print('out: ', end='')
    print(len(i.req))

'''currentNodeList = nodeList
levelList = []
epoch = 0
while len(currentNodeList):
    print("*******epoch:", epoch, "********")
    print("*******nodelist:", len(currentNodeList), "********")
    epoch += 1
    for node in currentNodeList:
        if len(node.req) == 0:
            levelList.append(node)
            node.level = 1
            currentNodeList.remove(node)
            continue
        require = node.req
        currentLv = -1
        hasNull = False
        for r in require:
            if r.level == -1: hasNull = True
            if r.level != 0 and r.level+1 > currentLv:
                currentLv = r.level+1
        node.level = currentLv
        if not hasNull:
            currentNodeList.remove(node)
            levelList.append(node)

for i in levelList:
    print("name:"+i.name+" ,level:", i.level)
'''

